<?php
declare (strict_types=1);

namespace app\common\model;

class ProductSpec extends Base
{
    protected function product(): object
    {
        return $this->hasOne(Product::class, 'id', 'pid')
            ->field('id,title,cate_1,cate_2,price,vip_price,icon,stock,sales,spec_open,status');
    }

    public static function getSettled($param, $user): array
    {
        try {
            $product = Product::where(['id' => $param['pid'], 'status' => 1])->find();
            if (empty($product)) {
                throw new \Exception('商品不存在或已下架');
            }
            if (!$param['num'] || $param['num'] < 1) {
                throw new \Exception('购买数量错误');
            }
            if ($product->spec_open == 2) {
                $specValue = parent::where(['pid' => $param['pid'], 'merge_title' => $param['spec']])->find();
                if (empty($specValue)) {
                    throw new \Exception('未查询到相关规格');
                }
                if ($param['num'] > $specValue->stock) {
                    throw new \Exception('商品库存不足');
                }
                $spec = $param['spec'];
                $icon = $specValue->icon ?: $product->icon;
                $vip_price = $specValue->vip_price;
            } else {
                if ($param['num'] > $product->stock) {
                    throw new \Exception('商品库存不足');
                }
                $spec = '';
                $icon = $product->icon;
                $vip_price = $product->vip_price;
            }
            $amount = round($vip_price * $param['num'], 2);
            $productAll[] = [
                'pid' => $product->id,
                'title' => $product->title,
                'spec' => $spec,
                'icon' => $icon,
                'num' => $param['num'],
                'vip_price' => $vip_price,
                'amount' => $amount
            ];
            $list = [
                'product' => $productAll,
                'amount' => sprintf('%.2f', $amount),
            ];

        } catch (\Exception $e) {

            return ['code' => -1, 'msg' => $e->getMessage()];
        }

        return ['code' => 1, 'msg' => 'success', 'data' => $list];
    }
}